<?php
/* 
 * name        : Internal » Contact
 * description : Create contact forms, including image or math based captchas.  Can also be used for 'send to a friend' forms.
 * context     : page
 * instructions: For configuration, see <a href="http://___CMSDOMAIN___/tools/contact/" target="_blank">___CMSDOMAIN___/tools/contact/</a>.
 * 
 */
global $db, $site, $smarty, $logger, $page;

$default_config = array(
	'to_name'            => '',
	'to_email'           => 'example@example.com',
	'from_name'          => '__name__',
	'from_email'         => '__email__',
	'subject'            => 'Website contact form',
	'submit_button_text' => 'Send',
	'body_error'         => '<p>You haven\'t completed all the required fields.</p>',
	'body_intro'         => '<p>Please complete the following form to send us a message.</p>',
	'body_mailfail'      => '<p>There were problems sending your message.  Please try again later.</p>',
	'body_success'       => '<p>Your message has been successfully sent.</p>',
	'mathcaptcha_intro'  => '<p>Please complete this simple sum to show you\'re not a spammer.</p>',
	'mathcaptcha_whatis' => 'What is __sum__?',
	'mathcaptcha_width'  => '100',
	'mathcaptcha_error'  => 'Please correct your answer.',
	'fields' => array(
		array(
			'type'       => 'text',
			'name'       => 'name',
			'label'      => 'Name *',
			'validation' => 'exists',
			'error_text' => 'You must enter your name.'
		),
		array(
			'type'       => 'text',
			'name'       => 'email',
			'label'      => 'Email *',
			'validation' => 'exists,email',
			'error_text' => 'You must enter your valid email address.'
		),
		array(
			'type'  => 'textarea',
			'name'  => 'message',
			'label' => 'Message'
		)
	)
);

$config = array_merge($default_config, parse_config($config));
$config['body_success'] .= "\n<script type='text/javascript'>var pageToTrack='{$page['full_path']}/ga-goal/';</script>\n";

if (isset($config['captcha'])) {
	if ($config['captcha'] == 'mathcaptcha') {
		if (!isset($_SESSION['mathcaptcha'])) {
			$_SESSION['mathcaptcha'] = array();
			$_SESSION['mathcaptcha']['num1'] = rand(1,5);
			$_SESSION['mathcaptcha']['num2'] = rand(1,5);
		}
		if ($_POST) {
			if ($_POST['mathcaptcha'] != $_SESSION['mathcaptcha']['num1'] + $_SESSION['mathcaptcha']['num2']) {
				$mathcaptcha_error = true;
				$error = true;
			}
		}
	}
}

if (isset($_REQUEST['mathcaptcha-img'])) {
	$gd = imagecreate($config['mathcaptcha_width'], 20);
	$bg = imagecolorallocate($gd, 255, 255, 255);
	imagecolortransparent($gd, $bg);
	$tx = imagecolorallocate($gd, 0, 0, 0);
	imagestring($gd, 3, 0, 0, str_replace("__sum__", "{$_SESSION['mathcaptcha']['num1']} + {$_SESSION['mathcaptcha']['num2']}", $config['mathcaptcha_whatis']), $tx);
	header('Content-type: image/png');
	imagepng($gd);
	imagedestroy($gd);
	exit;
}


if (isset($_POST['contact'])) {
	foreach($config['fields'] as $index => $field) {
		if ($field['type'] == 'file') {
			$_REQUEST['contact'][$field['name']] = $_FILES['contact']['name'][$field['name']];
			if (isset($field['max_size']) and $_FILES['contact']['size'][$field['name']] > $field['max_size']) {
				$config['fields'][$index]['_error'] = true;
			}
		}
		if (isset($field['validation']) and validate($_REQUEST['contact'][$field['name']], $field['validation']) === false) {
			$config['fields'][$index]['_error'] = true;
			$error = true;
		}
	}
	
	if (!isset($error)) {
		
		$to_name    = $config['to_name'];
		$to_email   = $config['to_email'];
		$from_name  = $config['from_name'];
		$from_email = $config['from_email'];
		$subject    = $config['subject'];
		
		$mail_body_text = '';
		$mail_body_html = "<html><body><table cellspacing='0' style='width:100%;border-bottom:1px solid #eee;font-size:12px;line-height:135%;font-family:Lucida Grande, Tahoma, Arial, sans-serif;'>\n";
		
		$field_counter = 0;
		foreach($config['fields'] as $field) {
			$field_counter++;
			if ($field['type'] == 'checkbox') {
				$_REQUEST['contact'][$field['name']] = join(', ', $_REQUEST['contact'][$field['name']]);
			}
			$mail_body_text .= strip_tags($field['label']) . ":\n";
			$mail_body_text .= $_REQUEST['contact'][$field['name']] . "\n\n";
			
			$mail_body_html .= "<tr style='background-color:#" . ($field_counter%2==0 ? 'F5F5F5' : 'FFFFFF') . "'>\n";
			$mail_body_html .= "<th style='vertical-align:top;color:#222;text-align:left;padding:7px 9px 7px 9px;border-top:1px solid #eee;'>" . $field['label'] . "</th>\n";
			$mail_body_html .= "<td style='vertical-align:top;color:#333;width:60%;padding:7px 9px 7px 0;border-top:1px solid #eee;'>" . nl2br(htmlentities($_REQUEST['contact'][$field['name']], ENT_COMPAT, 'UTF-8')) . "</td>\n";
			$mail_body_html .= "</tr>\n";
			
			$to_name    = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $to_name);
			$to_email   = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $to_email);
			$from_name  = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $from_name);
			$from_email = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $from_email);
			$subject    = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $subject);
		
			if (isset($config['mail_body_text'])) $config['mail_body_text'] = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $config['mail_body_text']);
			if (isset($config['mail_body_html'])) $config['mail_body_html'] = str_replace('__'.$field['name'].'__', $_REQUEST['contact'][$field['name']], $config['mail_body_html']);
		}
		$mail_body_html .= "</table></body></html>\n";
		
		if (isset($config['mail_body_text'])) $mail_body_text = $config['mail_body_text'];
		if (isset($config['mail_body_html'])) $mail_body_html = $config['mail_body_html'];
		
		$mail = new Webtaculous_Mail('UTF-8', $db, $site['id']);
		$mail->setBodyText($mail_body_text);
		$mail->setBodyHtml($mail_body_html);
		$mail->setFrom($from_email, $from_name);
		$mail->addTo($to_email, $to_name);
		$mail->setSubject($subject);
		if (isset($_FILES) and count($_FILES)) {
			foreach($_FILES['contact']['tmp_name'] as $key => $filename) {
				$attachment = $mail->createAttachment(file_get_contents($filename));
				$attachment->filename = $_FILES['contact']['name'][$key];
			}
		}
		if ($mail->send()) {
			$logger->info("Email sent from {$from_email} to {$to_email} with subject {$subject}");
			$result = $config['body_success'];
		} else {
			$logger->crit("Email failed from {$from_email} to {$to_email} with subject {$subject}");
			$result = $config['body_mailfail'];
		}
		
		if (isset($config['assign'])) {
			$smarty->assign($config['assign'], $result);
		} else {
			echo $result;
		}
		
		// destroy any mathcaptcha data so that a new challenge is generated next time.
		unset($_SESSION['mathcaptcha']);
		
		return;
		
	}
}

for ($index=0;$index<count($config['fields']);$index++) {
	if ($config['fields'][$index]['type'] == 'checkbox') {
		$config['fields'][$index]['default'] =  isset($config['fields'][$index]['default']) ? split(',', $config['fields'][$index]['default']) : array();
		if ($_POST and !isset($_POST['contact'][$config['fields'][$index]['name']])) {
			$_POST['contact'][$config['fields'][$index]['name']] = array();
		}
	}
	if ($config['fields'][$index]['type'] == 'select' or $config['fields'][$index]['type'] == 'checkbox' or $config['fields'][$index]['type'] == 'radio') {
		$values = split(',', $config['fields'][$index]['values']);
		$config['fields'][$index]['values'] = array();
		foreach($values as $value) {
			if (strpos($value, '|') !== false) {
				list($value, $label) = split('\|', $value);
			} else {
				$label = $value;
			}
			$config['fields'][$index]['values'][$value] = $label;
		}
	}
	
	if (isset($_REQUEST['contact'][$config['fields'][$index]['name']])) {
		if (is_array($_REQUEST['contact'][$config['fields'][$index]['name']])) {
			$config['fields'][$index]['current_value'] = array();
			for($i=0;$i<count($_REQUEST['contact'][$config['fields'][$index]['name']]);$i++) {
				$config['fields'][$index]['current_value'][] = $_REQUEST['contact'][$config['fields'][$index]['name']][$i];
			}
		} else {
			$config['fields'][$index]['current_value'] = $_REQUEST['contact'][$config['fields'][$index]['name']];
		}
	} elseif (isset($config['fields'][$index]['default'])) {
		if ($config['fields'][$index]['type'] == 'date') {
			$config['fields'][$index]['current_value'] = date((isset($config['fields'][$index]['datepicker_format']) ? str_replace(array('-dt', '-sl-', '-ds-', '-cc-'), array('.', '/', '-', ','), $config['fields'][$index]['datepicker_format']) : 'd/m/Y'), strtotime($config['fields'][$index]['default']));
		} else {
			$config['fields'][$index]['current_value'] = $config['fields'][$index]['default'];
		}
	} else {
		$config['fields'][$index]['current_value'] = '';
	}
	
}

if (isset($error)) $smarty->assign('error', $error);
if (isset($mathcaptcha_error)) $smarty->assign('mathcaptcha_error', $mathcaptcha_error);
$smarty->assign('config', $config);
if (isset($config['assign'])) {
	$smarty->assign($config['assign'], $smarty->fetch(dirname(__FILE__) . '/templates/contact.tpl.html'));
} else {
	$smarty->display(dirname(__FILE__) . '/templates/contact.tpl.html');
}

function validate($value, $validators) {
	if (!is_array($validators)) $validators = array_filter(explode(',', $validators));
	foreach ($validators as $validator) {
		@list($validator, $config) = explode(':', $validator, 2);
		if (!call_user_func('validate_' . $validator, $value, isset($config) ? $config : '')) {
			return false;
		}
	}
	return true;
}

function validate_exists($value, $vconfig) {
	if (!$value) return false;
	return true;
}

function validate_email($value, $vconfig) {
	if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+\.([a-zA-Z0-9\._-]+)+$/", $value)) return false;
	return true;
}

function validate_antispam($value, $vconfig) {
	if (preg_match("/^Cc:/i", $value)) return false;
	if (preg_match("/^Bcc:/i", $value)) return false;
	if (preg_match("/\nCc:/i", $value)) return false;
	if (preg_match("/\nBcc:/i", $value)) return false;
	return true;
}

function validate_regex($value, $vconfig) {
	if (!preg_match($vconfig, $value)) return false;
	return true;
}
